import axios from 'axios'
import {Message} from "element-ui";
import router from "@/router";
import Cookies from "js-cookie";
// create an axios instance
const service = axios.create({
  baseURL: 'http://localhost:3000', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
      if (config.url !== '/user/login') {
          const user = Cookies.get("user")
          if (!user) {
              router.push({path:'/login'})
          }
      }


      // const user = Cookies.get("user")
    // do something before request is sent

    //   if (getToken()) {
    //       config.headers['authorization'] = getToken()
    //   } else {
    //       router.push('/login')
    //   }

    return config
  },
  error => {
    return Promise.reject('err'+error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const resp = response.data

      if (resp.code !== 200) {
          Message({
              message: resp.msg || 'Error',
              type: 'error',
              duration: 5 * 1000
          })
      } else {
          return resp
      }
  },
  error => {
    return Promise.reject(error)
  }
)




export default service
